<template>
  <div class="interview-chat" :class="{ 'dark': isDark }">
    <div class="interview-container">
      <!-- 面试开始界面 -->
      <div v-if="!isInterviewStarted" class="interview-start">
        <h2>Java 面试模拟器</h2>
        <div class="input-area">
          <textarea
              v-model="interviewTopic"
              placeholder="请输入面试主题（可选，例如‘多线程’）..."
              rows="3"
          ></textarea>
          <button class="start-button" @click="startInterview">
            开始面试
          </button>
        </div>
      </div>

      <!-- 面试对话界面 -->
      <div v-else class="chat-main">
        <!-- 面试统计信息 -->
        <div class="interview-stats">
          <div class="stat-item">
            <span class="label">技术得分</span>
            <div class="progress-bar">
              <div
                  class="progress"
                  :style="{ width: `${technicalScore}%` }"
                  :class="{
                  'low': technicalScore < 30,
                  'medium': technicalScore >= 30 && technicalScore < 70,
                  'high': technicalScore >= 70
                }"
              ></div>
            </div>
            <span class="value">{{ technicalScore }}/100</span>
          </div>
          <div class="stat-item">
            <span class="label">当前问题数</span>
            <span class="value">{{ currentQuestion }}/{{ MAX_QUESTIONS }}</span>
          </div>
        </div>

        <div class="messages" ref="messagesRef">
          <ChatMessage
              v-for="(message, index) in currentMessages"
              :key="index"
              :message="message"
              :is-stream="isStreaming && index === currentMessages.length - 1"
          />
        </div>

        <div class="input-area">
          <textarea
              v-model="userInput"
              @keydown.enter.prevent="sendAnswer()"
              placeholder="请输入你的回答..."
              rows="2"
              ref="inputRef"
              :disabled="isInterviewOver"
          ></textarea>
          <button
              class="send-button"
              @click="sendAnswer()"
              :disabled="isStreaming || !userInput.trim() || isInterviewOver"
          >
            <PaperAirplaneIcon class="icon" />
          </button>
        </div>
      </div>

      <!-- 面试结束提示 -->
      <div v-if="isInterviewOver" class="interview-over" :class="{ 'success': technicalScore >= 90 }">
        <div class="result">{{ interviewResult }}</div>
        <button class="restart-button" @click="resetInterview">
          重新开始
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue'
import { useDark } from '@vueuse/core'
import { PaperAirplaneIcon } from '@heroicons/vue/24/outline'
import ChatMessage from '../components/ChatMessage.vue'
import { chatAPI } from '../services/api'

const isDark = useDark()
const messagesRef = ref(null)
const inputRef = ref(null)
const userInput = ref('')
const isStreaming = ref(false)
const currentChatId = ref(null)
const currentMessages = ref([])
const interviewTopic = ref('')
const isInterviewStarted = ref(false)
const isInterviewOver = ref(false)
const interviewResult = ref('')
const MAX_QUESTIONS = 10  // 最大问题数
const currentQuestion = ref(0)  // 当前问题计数
const technicalScore = ref(0)  // 技术得分

// 自动调整输入框高度
const adjustTextareaHeight = () => {
  const textarea = inputRef.value
  if (textarea) {
    textarea.style.height = 'auto'
    textarea.style.height = textarea.scrollHeight + 'px'
  }
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight
  }
}

// 开始面试
const startInterview = async () => {
  isInterviewStarted.value = true
  isInterviewOver.value = false
  interviewResult.value = ''
  currentChatId.value = Date.now().toString()
  currentMessages.value = []
  currentQuestion.value = 0
  technicalScore.value = 50  // 初始技术得分

  // 发送开始面试请求
  const startPrompt = interviewTopic.value
      ? `开始面试，主题：${interviewTopic.value}`
      : '开始面试'

  await sendAnswer(startPrompt)
}

// 重置面试
const resetInterview = () => {
  isInterviewStarted.value = false
  isInterviewOver.value = false
  interviewResult.value = ''
  currentMessages.value = []
  interviewTopic.value = ''
  userInput.value = ''
  currentQuestion.value = 0
  technicalScore.value = 0
}

// 发送回答
const sendAnswer = async (content) => {
  if (isStreaming.value || (!content && !userInput.value.trim())) return

  // 使用传入的 content 或用户输入框的内容
  const messageContent = content || userInput.value.trim()

  // 添加用户消息
  const userMessage = {
    role: 'user',
    content: messageContent,
    timestamp: new Date()
  }
  currentMessages.value.push(userMessage)

  // 清空输入并增加问题计数
  if (!content) {  // 只有在非传入内容时才清空输入框和计数
    userInput.value = ''
    adjustTextareaHeight()
    currentQuestion.value++  // 增加问题计数
  }
  await scrollToBottom()

  // 添加面试官消息占位
  const assistantMessage = {
    role: 'assistant',
    content: '',
    timestamp: new Date()
  }
  currentMessages.value.push(assistantMessage)
  isStreaming.value = true

  let accumulatedContent = ''

  try {
    // 发送请求
    const reader = await chatAPI.sendGameMessage(messageContent, currentChatId.value)
    const decoder = new TextDecoder('utf-8')

    while (true) {
      try {
        const { value, done } = await reader.read()
        if (done) break

        // 累积新内容
        accumulatedContent += decoder.decode(value)

        // 提取技术得分
        const scoreMatch = accumulatedContent.match(/技术得分[:：]\s*(\d+)/i)
        if (scoreMatch) {
          const newScore = parseInt(scoreMatch[1])
          if (!isNaN(newScore)) {
            technicalScore.value = Math.min(100, Math.max(0, newScore))

            // 当技术得分达到90时，面试通过
            if (technicalScore.value >= 90) {
              isInterviewOver.value = true
              interviewResult.value = '恭喜你！通过了本次 Java 面试！🎉'
            }
          }
        }

        // 更新消息内容
        await nextTick(() => {
          const updatedMessage = {
            ...assistantMessage,
            content: accumulatedContent
          }
          const lastIndex = currentMessages.value.length - 1
          currentMessages.value.splice(lastIndex, 1, updatedMessage)
        })
        await scrollToBottom()
      } catch (readError) {
        console.error('读取流错误:', readError)
        break
      }
    }

    // 检查是否达到最大问题数
    if (currentQuestion.value >= MAX_QUESTIONS) {
      isInterviewOver.value = true
      if (technicalScore.value >= 90) {
        interviewResult.value = '恭喜你！在最后一题后通过了 Java 面试！🎉'
      } else {
        interviewResult.value = `面试结束：问题数已达上限(${MAX_QUESTIONS}题)，当前技术得分为${technicalScore.value}，未能通过面试`
      }
    }
    // 检查是否面试结束
    else if (accumulatedContent.includes('面试失败') || accumulatedContent.includes('面试通过')) {
      isInterviewOver.value = true
      interviewResult.value = accumulatedContent.includes('面试通过')
          ? '恭喜你！通过了本次 Java 面试！🎉'
          : '很遗憾，你未能通过本次面试，请继续努力！'
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    assistantMessage.content = '抱歉，发生了错误，请稍后重试。'
  } finally {
    isStreaming.value = false
    await scrollToBottom()
  }
}

onMounted(() => {
  adjustTextareaHeight()
})
</script>

<style scoped lang="scss">
.interview-chat {
  position: fixed;
  top: 64px;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  background: var(--bg-color);
  overflow: hidden;
  z-index: 1;

  .interview-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    max-width: 1200px;
    width: 100%;
    margin: 0 auto;
    padding: 1.5rem 2rem;
    position: relative;
    height: 100%;
  }

  .interview-start {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 2rem;
    min-height: 400px;
    padding: 2rem;
    background: var(--bg-color);
    border-radius: 1rem;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);

    h2 {
      font-size: 2rem;
      color: var(--text-color);
      margin: 0;
      font-weight: 600;
    }

    .input-area {
      width: 100%;
      max-width: 600px;
      display: flex;
      flex-direction: column;
      gap: 1rem;

      textarea {
        width: 100%;
        padding: 1rem;
        border: 1px solid rgba(0, 0, 0, 0.1);
        border-radius: 0.5rem;
        resize: none;
        font-family: inherit;
        font-size: 1rem;
        line-height: 1.5;

        &:focus {
          outline: none;
          border-color: #1E88E5;
          box-shadow: 0 0 0 2px rgba(30, 136, 229, 0.1);
        }
      }

      .start-button {
        padding: 1rem 2rem;
        background: #1E88E5;
        color: white;
        border: none;
        border-radius: 0.5rem;
        font-size: 1.1rem;
        cursor: pointer;
        transition: background-color 0.3s;

        &:hover {
          background: #1565C0;
        }
      }
    }
  }

  .chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: rgba(255, 255, 255, 0.98);
    border-radius: 1rem;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    overflow: hidden;

    .interview-stats {
      position: sticky;
      top: 0;
      background: rgba(33, 33, 33, 0.9);
      color: white;
      padding: 1rem;
      z-index: 10;
      display: flex;
      gap: 2rem;
      justify-content: center;
      align-items: center;
      margin-bottom: 1rem;
      border-radius: 0.5rem;

      .stat-item {
        display: flex;
        align-items: center;
        gap: 0.5rem;

        .label {
          font-weight: 500;
        }

        .value {
          font-size: 1rem;
          font-weight: 500;
        }

        .progress-bar {
          width: 150px;
          height: 8px;
          background: rgba(255, 255, 255, 0.2);
          border-radius: 4px;
          overflow: hidden;

          .progress {
            height: 100%;
            transition: width 0.3s ease;
            border-radius: 4px;

            &.low {
              background: #EF5350;
            }

            &.medium {
              background: #FFB300;
            }

            &.high {
              background: #43A047;
            }
          }
        }
      }
    }

    .messages {
      flex: 1;
      overflow-y: auto;
      padding: 2rem;
    }

    .input-area {
      flex-shrink: 0;
      padding: 1.5rem 2rem;
      background: rgba(255, 255, 255, 0.99);
      border-top: 1px solid rgba(0, 0, 0, 0.05);
      display: flex;
      gap: 1rem;
      align-items: flex-end;

      textarea {
        flex: 1;
        resize: none;
        border: 1px solid rgba(0, 0, 0, 0.1);
        background: white;
        border-radius: 0.75rem;
        padding: 1rem;
        color: inherit;
        font-family: inherit;
        font-size: 1rem;
        line-height: 1.5;
        max-height: 150px;

        &:focus {
          outline: none;
          border-color: #1E88E5;
          box-shadow: 0 0 0 2px rgba(30, 136, 229, 0.1);
        }

        &:disabled {
          background: #f5f5f5;
          cursor: not-allowed;
        }
      }

      .send-button {
        background: #1E88E5;
        color: white;
        border: none;
        border-radius: 0.5rem;
        width: 2.5rem;
        height: 2.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: background-color 0.3s;

        &:hover:not(:disabled) {
          background: #1565C0;
        }

        &:disabled {
          background: #ccc;
          cursor: not-allowed;
        }

        .icon {
          width: 1.25rem;
          height: 1.25rem;
        }
      }
    }
  }

  .interview-over {
    position: absolute;
    bottom: 6rem;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(33, 33, 33, 0.9);
    color: white;
    padding: 1rem 2rem;
    border-radius: 0.5rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 1rem;

    .result {
      font-size: 1.1rem;
      font-weight: 500;
    }

    .restart-button {
      padding: 0.5rem 1rem;
      background: #1E88E5;
      color: white;
      border: none;
      border-radius: 0.25rem;
      cursor: pointer;
      transition: background-color 0.3s;

      &:hover {
        background: #1565C0;
      }
    }

    &.success {
      background: rgba(67, 160, 71, 0.9);

      .restart-button {
        background: #43A047;

        &:hover {
          background: #2E7D32;
        }
      }
    }
  }
}

.dark {
  .interview-start {
    .input-area {
      textarea {
        background: rgba(255, 255, 255, 0.05);
        border-color: rgba(255, 255, 255, 0.1);
        color: white;

        &:focus {
          border-color: #1E88E5;
          box-shadow: 0 0 0 2px rgba(30, 136, 229, 0.2);
        }
      }
    }
  }

  .chat-main {
    background: rgba(40, 40, 40, 0.98);
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);

    .input-area {
      background: rgba(30, 30, 30, 0.99);
      border-top: 1px solid rgba(255, 255, 255, 0.05);

      textarea {
        background: rgba(50, 50, 50, 0.95);
        border-color: rgba(255, 255, 255, 0.1);
        color: white;

        &:focus {
          border-color: #1E88E5;
          box-shadow: 0 0 0 2px rgba(30, 136, 229, 0.2);
        }

        &:disabled {
          background: rgba(30, 30, 30, 0.95);
        }
      }
    }

    .interview-stats {
      background: rgba(33, 33, 33, 0.95);
    }
  }
}
</style>
